package hmh;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.List;

public class Combine {
    static String combinedFilePath = "/Users/hanminghao/Downloads/Transfer/combinedFile1.xml";
    private static final int TAILLENGTH = 14;
    private static final int HEADLENGTH = 972;
    public static void myCombineXML(List<String> fileNames) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel combinedFileChannel = null;
        try {
            sourceChannel = new FileInputStream(fileNames.get(0)).getChannel();
            combinedFileChannel = new FileOutputStream(combinedFilePath).getChannel();
//            sourceChannel.transferTo(HEADLENGTH,tail,combinedFileChannel);
            sourceChannel.transferTo(0,sourceChannel.size() - TAILLENGTH,combinedFileChannel);
            for (int index=1;index<fileNames.size()-2;index++){
                sourceChannel.close();
                sourceChannel = new FileInputStream(fileNames.get(index)).getChannel();
                sourceChannel.transferTo(HEADLENGTH,sourceChannel.size() - TAILLENGTH - HEADLENGTH,combinedFileChannel);
            }
            sourceChannel = new FileInputStream(fileNames.get(fileNames.size()-1)).getChannel();
            sourceChannel.transferTo(HEADLENGTH,sourceChannel.size() ,combinedFileChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (sourceChannel!=null){
                    sourceChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (combinedFileChannel!=null){
                    combinedFileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
